package com.ilovepostcard.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.ilovepostcard.Actions;
import com.ilovepostcard.MainActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.controller.BaseAsyncTask;
import com.ilovepostcard.controller.PostcardController;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.model.ShareTextConfig;
import com.ilovepostcard.model.User;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class ThirdPartyLoginUtil {

    private static final String SINA_APP_KEY = "1759153508";
    private static final String SINA_APP_SECRET = "2f46eefcec100fcb6d00b1c2202733ea";
    private static final String SINA_REDIRECT_URL = "http://www.ilovepostcard.com";
    
//    private static final String TENCENT_APP_KEY = "801251103";
//    private static final String TENCENT_APP_SECRET = "ae4cec65753fabf56f2e0cd082b54060";
    private static final String TENCENT_APP_KEY = "100651352";
    private static final String TENCENT_APP_SECRET = "69d0e25ac0ed8948d808cfe8cb3700c0";
    private static final String TENCENT_REDIRECT_URL = "http://www.ilovepostcard.com";
    
    private static final String WEIXIN_APP_ID = "wx1e10d97bb329f251";
    private static final String WEIXIN_APP_SECRET = "00b3ae75208d6d6297a633235d39e495";

    public static final int TENCENT_LOGIN_REQUEST_CODE = 19850602;
    public static final int TENCENT_SHARE_REQUEST_CODE = 19860602;
    
    public static void sinaLogin(Activity activity) {
        Weibo weibo = Weibo.getInstance();
        weibo.setupConsumerConfig(SINA_APP_KEY, SINA_APP_SECRET);

        // Oauth2.0
        // 隐式授权认证方式
        weibo.setRedirectUrl(SINA_REDIRECT_URL);// 此处回调页内容应该替换为与appkey对应的应用回调页
        // 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
        // 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
        // 应用回调页不可为空

        weibo.authorize(activity, new AuthDialogListener(activity));
    }
    
    static class ShareDialogListen implements WeiboDialogListener {

        ShareTextConfig config;
        Activity activity;
        long pid;
        
        public ShareDialogListen(Activity activity, ShareTextConfig config, long pid) {
            super();
            this.config = config;
            this.activity = activity;
            this.pid = pid;
        }

        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            final AccessToken accessToken = new AccessToken(token, SINA_APP_SECRET);
            accessToken.setExpiresIn(expires_in);
            Weibo.getInstance().setAccessToken(accessToken);
//            try {
//                String filePath = null;
//                FileOutputStream fos = null;
//                try {
//                Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
//                if (postcard != null && postcard.image != null) {
//                    fos = new FileOutputStream(Constants.TEMP_CAMERA_IMAGE_PATH);
//                    postcard.image.compress(CompressFormat.JPEG, 100, fos);
//                    filePath = Constants.TEMP_CAMERA_IMAGE_PATH;
//                }
//                } catch(Exception e) {
//                    
//                } finally {
//                    if (fos != null) {
//                        try {
//                            fos.close();
//                        } catch(Exception exception) {
//                            
//                        }
//                    }
//                }
//                
//                Weibo.getInstance().share2weibo(activity, accessToken.getToken(), accessToken.getSecret(), config.Body, filePath);
//            } catch (WeiboException e) {
//                e.printStackTrace();
//            }
            
            //start
            new AsyncTask<Void, Void, Void>() {

                ProgressDialog pd;
                boolean download;

                @Override
                protected Void doInBackground(Void... params) {
                	
                	download = sendPostcardViewImage(pid,Constants.TEMP_SHARE_IMAGE_PATH);
                	if(!download)
                		download = downloadImage(config.PostcardUrl, Constants.TEMP_SHARE_IMAGE_PATH);
                    return null;
                }

                @Override
                protected void onPreExecute() {
                    pd = new ProgressDialog(activity);
                    pd.setMessage(activity.getText(R.string.loading_data));
                    pd.show();
                }

                @Override
                protected void onPostExecute(Void result) {
                    try {
                        pd.dismiss();
                    } catch (Exception e) {

                    }
                    if (download) {
                        
                        try {
                        	Weibo.getInstance().share2weibo(activity, accessToken.getToken(), accessToken.getSecret(), config.Body, Constants.TEMP_SHARE_IMAGE_PATH);
                        } catch (WeiboException e) {
                        	e.printStackTrace();
                        }
                        
                    } else {
                        Toast.makeText(activity, "获取图片失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                }

            }.execute();
            //end
        }

        @Override
        public void onError(DialogError e) {
            Toast.makeText(activity, "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(activity, "Auth cancel", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(activity, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
        
    }

    static class AuthDialogListener implements WeiboDialogListener {

        private Activity activity;

        public AuthDialogListener(Activity activity) {
            super();
            this.activity = activity;
        }

        @Override
        public void onComplete(Bundle values) {
            String token = values.getString("access_token");
            String expires_in = values.getString("expires_in");
            final AccessToken accessToken = new AccessToken(token, SINA_APP_SECRET);
            accessToken.setExpiresIn(expires_in);
            Weibo.getInstance().setAccessToken(accessToken);
            final String uid = values.getString("uid");

            new BaseAsyncTask() {

                ProgressDialog pd;
                String name;
                String nick;
                String imageUrl;

                @Override
                protected void _onPreExecute() {
                    pd = new ProgressDialog(activity);
                    pd.setMessage("获取新浪用户信息...");
                    pd.show();
                }

                @Override
                protected void _doInBackground() {
                    String url = Weibo.SERVER + "users/show.json";
                    WeiboParameters bundle = new WeiboParameters();
                    bundle.add("source", Weibo.getAppKey());
                    bundle.add("uid", uid);
                    try {
                        String rlt = Weibo.getInstance().request(activity, url, bundle, "GET",
                                Weibo.getInstance().getAccessToken());
                        JSONObject jsonObject = new JSONObject(rlt);
                        name = jsonObject.getString("id");
                        nick = jsonObject.getString("screen_name");
                        imageUrl = jsonObject.getString("profile_image_url");
                    } catch (WeiboException e) {
                        e.printStackTrace();
                    } catch (JSONException exception) {
                        exception.printStackTrace();
                    }
                }

                @Override
                protected void _onPostExecute() {
                    pd.dismiss();
                    if (nick != null && name != null) {
                        User user = new User();
                        /* the result is uid */
                        user.Username = name;
                        user.Nickname = nick;
                        
                        new ServerAsyncTask(activity) {
                            
                            @Override
                            protected void onSuccess(PostcardResult result) {
                                User user = new User();
                                /* the result is uid */
                                user.UserID = result.getResult();
                                user.Username = name;
                                UserController.saveLoginUser(context, user);
                                UserController.saveThirdPartySecret(context, "sina", accessToken.getToken(), accessToken.getSecret());
                                /* now only used to notify the LoginActivity to finish itself. */
                                context.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
                                ((Activity)context).finish();
                                Intent intent = new Intent(context, MainActivity.class);
                                context.startActivity(intent);
//                                Toast.makeText(activity, "你好 " + nick, Toast.LENGTH_SHORT).show();
                                
                                ThirdPartyLoginUtil.uploadThirdPartyHead(activity, imageUrl, user.UserID);
                            }
                            
                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer().userLoginFromOpen(name, nick, IServer.OPEN_TYPE_SINA);
                            }
                        }.execute();
                        
//                        UserController.saveLoginUser(activity, user);
//                        /* now only used to notify the LoginActivity to finish itself. */
//                        activity.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
//                        activity.finish();
//                        Intent intent = new Intent(activity, MainActivity.class);
//                        activity.startActivity(intent);
//                        Toast.makeText(activity, "Hello " + nick, Toast.LENGTH_SHORT).show();
                    } else {
//                        Toast.makeText(activity, "获取微薄用户信息失败", Toast.LENGTH_SHORT).show();
                    }
                }

            }.execute();

            
            
        }

        @Override
        public void onError(DialogError e) {
            Toast.makeText(activity, "Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(activity, "Auth cancel", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(activity, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    public static void tencentLogin(Activity activity) {
        OAuthV2 oAuth;
        oAuth = new OAuthV2(TENCENT_REDIRECT_URL);
        oAuth.setClientId(TENCENT_APP_KEY);
        oAuth.setClientSecret(TENCENT_APP_SECRET);
        Intent intent = new Intent(activity, OAuthV2AuthorizeWebView.class);
        intent.putExtra("oauth", oAuth);
        activity.startActivityForResult(intent, TENCENT_LOGIN_REQUEST_CODE);
    }
    
    public static void uploadThirdPartyHead(final Context context, final String headUrl, final long uid) {
        /* download */
        new BaseAsyncTask() {
            
            File headFile;
            
            @Override
            protected void _doInBackground() {
                if (DrawableManager.getInstance().fetchDrawable(headUrl) != null) {
                    headFile = DrawableManager.getInstance().getLocalCachedFile(headUrl);
                }
            }
            
            @Override
            protected void _onPostExecute() {
                if (headFile == null)
                    return;
                new ServerAsyncTask(context) {
                    
                    protected boolean isShowDialog() {
                        return false;
                    }
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        final String skey = result.getUploadSKey();
                        new ServerAsyncTask(context) {
                            
                            protected boolean isShowDialog() {
                                return false;
                            }
                            
                            @Override
                            protected void onSuccess(PostcardResult result) {
//                                Toast.makeText(context, "获取微博头像", Toast.LENGTH_SHORT).show();
                                new Thread(new Runnable() {
                                    
                                    @Override
                                    public void run() {
                                        try {
                                            PostcardResult result = ServerFactory.getServer().getUserInfo("", uid);
                                            User user = result.getUser();
                                            UserController.saveDetailUser(context, user);
                                        } catch (Exception e) {

                                        }
                                    }
                                }).start();
                            }
                            
                            @Override
                            protected PostcardResult doRequest() {
                                return ServerFactory.getServer().uploadFile(IServer.FILE_TYPE_HEAD_IMAGE, System.currentTimeMillis()+".jpg", skey, uid, 0, 0, 100, 100, 0, headFile);
                            }
                        }.execute();
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().getUploadSKey();
                    }
                }.execute();
                
            }
        }.execute();
        
        
    }
    
    
    private static String randomStringFrom(String[] strs) {
        int length = strs.length;
        Random random = new Random(System.currentTimeMillis());
        int index = random.nextInt(length);
        return strs[index];
    }
    
    public static void shareToSinaWeibo(final Context context, final long pid) {
        new ServerAsyncTask(context) {
            
            @Override
            protected void onSuccess(PostcardResult result) {
                final ShareTextConfig shareTextConfig = result.getShareTextConfig2();
                
                if (isSinaWeiboInstalled(context)) {
                    new AsyncTask<Void, Void, Void>() {

                        ProgressDialog pd;
                        boolean download;

                        @Override
                        protected Void doInBackground(Void... params) {
                        	
                        	download = sendPostcardViewImage(pid,Constants.TEMP_SHARE_IMAGE_PATH);
                        	if(!download)
                        		download = downloadImage(shareTextConfig.PostcardUrl, Constants.TEMP_SHARE_IMAGE_PATH);
                            return null;
                        }

                        @Override
                        protected void onPreExecute() {
                            pd = new ProgressDialog(context);
                            pd.setMessage(context.getText(R.string.loading_data));
                            pd.show();
                        }

                        @Override
                        protected void onPostExecute(Void result) {
                            try {
                                pd.dismiss();
                            } catch (Exception e) {

                            }
                            if (download) {
                                Intent shareIntent = new Intent();
                                shareIntent.setAction(Intent.ACTION_SEND);
                                shareIntent.setClassName(SINA_PACKAGE, SINA_SEND_ACTIVITY);

                                shareIntent.putExtra(Intent.EXTRA_TEXT, shareTextConfig.Body);

                                shareIntent.putExtra(Intent.EXTRA_STREAM,
                                        Uri.fromFile(new File(Constants.TEMP_SHARE_IMAGE_PATH)));

                                shareIntent.setType("image/jpeg");
                                context.startActivity(shareIntent);
                            } else {
                                Toast.makeText(context, "获取图片失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }.execute();
                    return;
                }
                
                
                
                String type = UserController.getThirdPartyType(context);
                if (false && "sina".equals(type)) {
                    Weibo weibo = Weibo.getInstance();
                    weibo.setupConsumerConfig(SINA_APP_KEY, SINA_APP_SECRET);
                    String[] tokens = UserController.getSinaAccessToken(context);
                    // Oauth2.0
                    // 隐式授权认证方式
                    weibo.setRedirectUrl(SINA_REDIRECT_URL);// 此处回调页内容应该替换为与appkey对应的应用回调页
                    try {
                        String filePath = null;
                        FileOutputStream fos = null;
                        try {
                        Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
                        Bitmap image = postcard.getTmpEditPC();
                        if (postcard != null && image != null) {
                            fos = new FileOutputStream(Constants.TEMP_CAMERA_IMAGE_PATH);
                            image.compress(CompressFormat.JPEG, 100, fos);
                            filePath = Constants.TEMP_CAMERA_IMAGE_PATH;
                        }
                        } catch(Exception e) {
                            
                        } finally {
                            if (fos != null) {
                                try {
                                    fos.close();
                                } catch(Exception exception) {
                                    
                                }
                            }
                        }
                    weibo.share2weibo((Activity)context, tokens[0], tokens[1], shareTextConfig.Body, filePath);
                    } catch (WeiboException e) {
                        e.printStackTrace();
                    }
                } else {
                    Weibo weibo = Weibo.getInstance();
                    weibo.setupConsumerConfig(SINA_APP_KEY, SINA_APP_SECRET);

                    // Oauth2.0
                    // 隐式授权认证方式
                    weibo.setRedirectUrl(SINA_REDIRECT_URL);// 此处回调页内容应该替换为与appkey对应的应用回调页
                    // 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
                    // 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
                    // 应用回调页不可为空

                    weibo.authorize((Activity)context, new ShareDialogListen((Activity)context, shareTextConfig, pid));
                }
            }
            
            @Override
            protected PostcardResult doRequest() {
                User loginUser = UserController.getLoginUser(context);
                return ServerFactory.getServer().getShareTextConfig(IServer.TEXT_CONFIG_TYPE_SHARE, loginUser.UserID, pid);
            }
        }.execute();
    }
    
    public static void shareToTencent(final Context context, final long pid) {
        if (isTencentWeiboInstalled(context)) {
            new ServerAsyncTask(context) {

                @Override
                protected void onSuccess(PostcardResult result) {
                    final ShareTextConfig shareTextConfig = result.getShareTextConfig2();

                    new AsyncTask<Void, Void, Void>() {

                        ProgressDialog pd;
                        boolean download;

                        @Override
                        protected Void doInBackground(Void... params) {
                        	download = sendPostcardViewImage(pid,Constants.TEMP_SHARE_IMAGE_PATH);
                        	if(!download)
                        		download = downloadImage(shareTextConfig.PostcardUrl, Constants.TEMP_SHARE_IMAGE_PATH);
                            return null;
                        }

                        @Override
                        protected void onPreExecute() {
                            pd = new ProgressDialog(context);
                            pd.setMessage(context.getText(R.string.loading_data));
                            pd.show();
                        }

                        @Override
                        protected void onPostExecute(Void result) {
                            try {
                                pd.dismiss();
                            } catch (Exception e) {

                            }
                            if (download) {
                                Intent shareIntent = new Intent();
                                shareIntent.setAction(Intent.ACTION_SEND);
                                shareIntent.setClassName(TENCENT_PACKAGE, TENCENT_SEND_ACTIVITY);

                                shareIntent.putExtra(Intent.EXTRA_TEXT, shareTextConfig.Body);

                                shareIntent.putExtra(Intent.EXTRA_STREAM,
                                        Uri.fromFile(new File(Constants.TEMP_SHARE_IMAGE_PATH)));

                                shareIntent.setType("image/jpeg");
                                context.startActivity(shareIntent);
                            } else {
                                Toast.makeText(context, "获取图片失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }.execute();

                }

                @Override
                protected PostcardResult doRequest() {
                    User loginUser = UserController.getLoginUser(context);
                    return ServerFactory.getServer().getShareTextConfig(IServer.TEXT_CONFIG_TYPE_SHARE,
                            loginUser.UserID, pid);
                }
            }.execute();
            return;
        }

        OAuthV2 oAuth;
        oAuth = new OAuthV2(TENCENT_REDIRECT_URL);
        oAuth.setClientId(TENCENT_APP_KEY);
        oAuth.setClientSecret(TENCENT_APP_SECRET);
        Intent intent = new Intent((Activity) context, OAuthV2AuthorizeWebView.class);
        intent.putExtra("oauth", oAuth);
        ((Activity) context).startActivityForResult(intent, TENCENT_SHARE_REQUEST_CODE);
    }
    
    public static void shareToWeiXin(final Context context, final long pid) {
        new ServerAsyncTask(context) {
            
            @Override
            protected void onSuccess(PostcardResult result) {
                ShareTextConfig shareTextConfig = result.getShareTextConfig2();
                IWXAPI api = WXAPIFactory.createWXAPI(context, WEIXIN_APP_ID, true);
                api.registerApp(WEIXIN_APP_ID);
                WXTextObject textObj = new WXTextObject();
                textObj.text = shareTextConfig.Body;
                //case 1
                /* WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObj;
                msg.description = shareTextConfig.Body;
                Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
                if (postcard != null && postcard.image != null) {
                    msg.setThumbImage(postcard.image);
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = System.currentTimeMillis()+"";
                req.message = msg;
                api.sendReq(req);*/
            	
                String filePath = null;
                FileOutputStream fos = null;
                Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
                Bitmap pcView = postcard == null ? null : postcard.getTmpEditPCView();
                Bitmap image  = null;
                Bitmap shareImage = null; 
                if(pcView == null)
                {
                	image = postcard == null ? null : postcard.getTmpEditPC();
                }
                if(postcard == null || postcard.id !=pid|| (pcView == null && image == null))
                	return ;
                if (postcard != null) {
                	if(pcView != null)
                		shareImage = pcView;
                	else if(image != null)
                		shareImage = image;
                }
                if(shareImage!= null)
            	{
                	try {
                        fos = new FileOutputStream(Constants.TEMP_SHARE_IMAGE_PATH);
                        shareImage.compress(CompressFormat.JPEG, 100, fos);
                        filePath = Constants.TEMP_SHARE_IMAGE_PATH;
                    
                    } catch(Exception e) {
                        
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch(Exception exception) {
                                
                            }
                        }
                    }
            	}
                
                
                
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setPackage("com.tencent.mm");
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "分享美好是对情谊最好的解读！\n来源：恋上明信片"/*shareTextConfig.Body*/);
                shareIntent.setType("image/png");
                if (filePath != null) {
                    File file = new File(filePath);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                }
                
                try
                {
                	context.startActivity(shareIntent);
                }
                catch(ActivityNotFoundException e)
                {
                	Toast.makeText(context, "你还没有安装微信,所以暂时不能分享到微信！", Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            protected PostcardResult doRequest() {
                User loginUser = UserController.getLoginUser(context);
                return ServerFactory.getServer().getShareTextConfig(IServer.TEXT_CONFIG_TYPE_SHARE, loginUser.UserID, pid);
            }
        }.execute();
    }
    
    public static void shareToOther(final Context context, final long pid) {
        new ServerAsyncTask(context) {
            
            @Override
            protected void onSuccess(PostcardResult result) {
                final ShareTextConfig shareTextConfig = result.getShareTextConfig2();
                
                new AsyncTask<Void, Void, Void>() {

                    ProgressDialog pd;
                    boolean download;

                    @Override
                    protected Void doInBackground(Void... params) {
                    	
                    	download = sendPostcardViewImage(pid,Constants.TEMP_SHARE_IMAGE_PATH);
                    	if(!download)
                    		download = downloadImage(shareTextConfig.PostcardUrl, Constants.TEMP_SHARE_IMAGE_PATH);
                        return null;
                    }

                    @Override
                    protected void onPreExecute() {
                        pd = new ProgressDialog(context);
                        pd.setMessage(context.getText(R.string.loading_data));
                        pd.show();
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        try {
                            pd.dismiss();
                        } catch (Exception e) {

                        }
                        if (download) {
                            Intent shareIntent = new Intent(Intent.ACTION_SEND);
                            shareIntent.putExtra(Intent.EXTRA_TEXT, shareTextConfig.Body);
                            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Constants.TEMP_SHARE_IMAGE_PATH)));
                            shareIntent.setType("image/jpeg");
                            context.startActivity(Intent. createChooser(shareIntent, "分享" ));
                        } else {
                            Toast.makeText(context, "获取图片失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }

                }.execute();
            }
            
            @Override
            protected PostcardResult doRequest() {
                User loginUser = UserController.getLoginUser(context);
                return ServerFactory.getServer().getShareTextConfig(IServer.TEXT_CONFIG_TYPE_SHARE, loginUser.UserID, pid);
            }
        }.execute();
    }
    
    private static final String SINA_PACKAGE = "com.sina.weibo";
    private static final String SINA_SEND_ACTIVITY = "com.sina.weibo.EditActivity";
    private static final String TENCENT_PACKAGE = "com.tencent.WBlog";
    private static final String TENCENT_SEND_ACTIVITY = "com.tencent.WBlog.intentproxy.TencentWeiboIntent";
    
    private static boolean isSinaWeiboInstalled(Context context) {
//        return false;
        return isPackageExists(context, SINA_PACKAGE);
    }
    
    private static boolean isTencentWeiboInstalled(Context context) {
//        return false;
        return isPackageExists(context, TENCENT_PACKAGE);
    }
    
    private static boolean isPackageExists(Context context, String targetPackage) {
        PackageManager pm = context.getPackageManager();
        try {
            pm.getPackageInfo(targetPackage, PackageManager.GET_META_DATA);
        } catch (NameNotFoundException e) {
            return false;
        }
        return true;
    }
    
    private static InputStream fetch(String urlString) throws MalformedURLException, IOException {
        URLConnection uc = new URL(urlString).openConnection();
        uc.setConnectTimeout(60000);
        uc.setReadTimeout(60000);
        return uc.getInputStream();
    }
    
    private static boolean sendPostcardViewImage(long pid,String imagePath)
    {
        FileOutputStream fos = null;
        Postcard postcard = PostcardController.getInstance().getCurrentPostCard();
        Bitmap pcView = postcard == null ? null : postcard.getTmpEditPCView();
        Bitmap image  = null;
        
        if(pcView == null)
        {
        	image = postcard == null ? null : postcard.getTmpEditPC();
        }
        if(postcard == null || postcard.id !=pid|| (pcView == null && image == null))
        	return false;

        Bitmap shareImage = null;
        if (postcard != null) {
        	if(pcView != null)
        		shareImage = pcView;
        	else if(image != null)
        		shareImage = image;
        }
        if(shareImage!= null)
    	{
        	try {
                fos = new FileOutputStream(imagePath);
                shareImage.compress(CompressFormat.JPEG, 100, fos);
            
            } catch(Exception e) {
                
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch(Exception exception) {
                        
                    }
                }
            }
    	}
        return true;
    }

    private static boolean downloadImage(String imageUrl, String imagePath) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = fetch(imageUrl);
            fos = new FileOutputStream(imagePath);
            int read = 0;
            byte[] buffer = new byte[1 << 13];
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            BufferedInputStream bis = new BufferedInputStream(is);
            while ((read = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, read);
            }
            bos.flush();
            bos.close();
            return true;
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } catch (Throwable e) {

        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (Exception e2) {

                }
            if (fos != null)
                try {
                    fos.close();
                } catch (Exception e2) {

                }
        }
        return false;
    }
}
